<?php
declare(strict_types=1);
namespace cms\wechat\service;

use cms\wechat\model\PlatformModel;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request;

class PlatformService extends CommonService
{
    /**
     * @Inject()
     * @var PlatformModel
     */
    public PlatformModel $model;

    public function initApplication(PlatformModel $platformModel): \EasyWeChat\OpenPlatform\Application
    {
        // 实例化应用
        $application = Factory::openPlatform([
            'app_id' => $platformModel->app_id,
            'secret' => $platformModel->app_secret,
            'token' => $platformModel->app_token,
            'aes_key' => $platformModel->app_key
        ]);

        // region 替换请求 +++++
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $get = $request->getQueryParams();
        $post = $request->getParsedBody();
        $cookie = $request->getCookieParams();
        $uploadFiles = $request->getUploadedFiles() ?? [];
        $server = $request->getServerParams();
        $xml = $request->getBody()->getContents();
        $files = [];
        /** @var \Hyperf\HttpMessage\Upload\UploadedFile $v */
        foreach ($uploadFiles as $k => $v) {
            $files[$k] = $v->toArray();
        }
        $new_request = new Request($get, $post, [], $cookie, $files, $server, $xml);
        $new_request->headers = new HeaderBag($request->getHeaders());
        $application->rebind('request', $new_request);
        // endregion


        $handler = new CoroutineHandler();
        $stack = HandlerStack::create($handler);
        // 设置HttpClient
        $http_config = $application->config->get('http', []);
        $http_config['handler'] = $stack;
        $application->rebind('http_client', new Client($http_config));

        // 替换缓存
        $cache = ApplicationContext::getContainer()->get(CacheInterface::class);
        $application->rebind('cache', $cache);
        return $application;
    }

}